

let params = {
  pagenum:1,
  pagesize:3,
}
// 数据渲染
function num() {
  console.log(params);
  $.ajax({
    type: 'get',
    url: '/admin/users',
    // headers:Authorization,
    data:params,
    success:function (res) {
      console.log(res);
      let {status,data,total} = res
      let str = ''
      if (status === 0){
        data.forEach(item => {
          str += `
          <tr>
              <td>${item.id}</td>
              <td>${item.username}</td>
              <td>${item.nickname}</td>
              <td>${item.email}</td>
              <td>
                <button data-id="${item.id}" type="button" class="layui-btn layui-btn-xs ">
                  <a style="color: #fff" target="iframeArea" href="./edit.html?id=${item.id}">编辑</a>
                </button>
                <button data-id="${item.id}" type="button"
                  class="layui-btn layui-btn-xs layui-btn-danger delete">删除</button>
                <button data-id="${item.id}" type="button"
                  class="layui-btn layui-btn-xs layui-btn-normal delete">重置密码</button>
              </td>
            </tr>
             `
        })
      }
      $('tbody').html(str)
      sum(total)
      // console.log(res.total);
    }
  })
}
num()
// console.log(params.pagenum)
// console.log(params.pagesize)

// 分页
let laypage = layui.laypage
function sum(total) {
  laypage.render({
    elem: 'articlePage',
    count: total, //数据总数，从服务端得到
    curr: params.pagenum,
    limit: params.pagesize,
    limits: [2,3,5,10],
    layout: ['prev','page','next','skip','count','limit'],
    jump: function(obj, first){
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数
      //首次不执行
      if(!first){
        params.pagenum = obj.curr
        params.pagesize = obj.limit
        num()
      }
    }
  })
}

// 删除
$('.layui-table tbody').on('click','.layui-btn-danger', function () {
  let id = $(this).data('id')
  layer.confirm('确定删除吗?', function(index){
   $.ajax({
     type:'DELETE',
     url:`/admin/users/${id}`,
     success:function (res) {
      //  console.log(res);
       num()
     }
   })
   layer.close(index);
  }); 
})

// 重置密码
$('.layui-table tbody').on('click','.layui-btn-normal', function () {
  addIndex = layer.open({
    type: 1,
    title: '重置密码',
    content: $('#repwd-form-tpl').html(),
    area: ['500px', '250px']
  })
  let id = $(this).data('id')
  console.log(id);
  $('#repwd-form').on('submit','#btn',function (e) {
    e.preventDefault()
    $.ajax({
      type:'PUT',
      url:`/admin/users/${id}`,
      data:{
        password: $('#repwd-form input[name=password]').val()
      },
      success:function (res) {
        layer.msg(res.message)
        layer.close(index)
      }
    })
  })
})
let form = layui.form
form.verify({
  // 密码长度
  // 判断密码是否一致
  same: val => {
    let pwd = $('.pwd').val();
    if (pwd !== val) {
      return '两次密码不一致'
    }
  }
})
